package com.story.web.shiro.dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.druid.support.spring.stat.annotation.Stat;
import com.story.domain.Page;
import com.story.domain.SessionInfo;
import com.story.service.ISessionService;
import com.story.web.utils.SerializableUtils;

public class UserOldSessionDao extends CachingSessionDAO {
	@Autowired
	private ISessionService sessionService;
	@Override
	protected void doUpdate(Session session) {	
		if(session instanceof ValidatingSession && !((ValidatingSession)session).isValid()){
			//如果会话过期/停止 没必要再更新了  
			return;
		}
		PrincipalCollection principalCollection =
		(PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);		
		if(principalCollection ==null){
			return;
		}
		String username = (String) principalCollection.getPrimaryPrincipal();		
		if(session.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY)!=null
				&& session.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY) instanceof Boolean){
			Boolean authenticated = (Boolean) session.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
			
			if(authenticated){
				sessionService.update(username,SerializableUtils.serialize(session),session.getLastAccessTime(),session.getId().toString());	
			}
		}
		
		
		

	}

	@Override
	protected void doDelete(Session session) {
		SessionInfo info = sessionService.querySessionById(session.getId().toString());
		if(info == null){
			return;
		}
		Date quitTime = new Date(System.currentTimeMillis());
		sessionService.updateSessionWithLogout(quitTime, false, session.getId().toString());
	}

	@Override
	protected Serializable doCreate(Session session) {
		String host = session.getHost();	
		String username = (String) SecurityUtils.getSubject().getPrincipal();
		String ses = SerializableUtils.serialize(session);
		Date loginTime = session.getStartTimestamp();
		SessionInfo info = new SessionInfo();
		Serializable sessionid = generateSessionId(session);
		assignSessionId(session, sessionid);
		info.setId(session.getId().toString());
		info.setSession(ses);
		info.setUsername(username);
		info.setAccessIp(host);
		info.setLoginTime(loginTime);
		info.setStatus(true);
		
		sessionService.create(info);
		return session.getId();
	}


	/* (non-Javadoc)
	 * @see org.apache.shiro.session.mgt.eis.CachingSessionDAO#getActiveSessions()
	 */
	public Collection<SessionInfo> getActiveSessions(Page page) {
		return sessionService.findSomeByLimit(page);
		
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public List<SessionInfo> listActiveSessionsWithLimit(Integer pageNum,Integer pageSize){
		List<SessionInfo> list = sessionService.findAll();
		Integer count = sessionService.totalCount();
		if(pageNum<1 || pageSize<0){
			throw new IllegalArgumentException("参数错误!!");
		}
		Integer startIndex = (pageNum - 1) * pageSize;
		Integer toIndex = pageSize * pageNum - 1;
		if(startIndex<0){
			startIndex = 0;
		}
		if(toIndex > count){
			toIndex = count;
		}
		System.out.println(startIndex+"---"+toIndex);
		if(startIndex<0 || startIndex > count){
			throw new RuntimeException("计算出现错误");
		}
		if(toIndex<0 || toIndex > count){
			throw new RuntimeException("计算出现错误");
		}
		return list.subList(startIndex, toIndex);
	}
	

}
